const { app, BrowserWindow, Menu, Tray, nativeImage } = require("electron");
const path = require("path");

let mainWindow = null;
let tray = null;

app
  .whenReady()
  .then(createTray)
  .then(createWindow)
  .catch((err) => {
    console.error(err);
  });

//系统托盘
function createTray() {
  iconPath = path.join(__dirname, "./assets/tray.png");
  tray = new Tray(nativeImage.createFromPath(iconPath));
  var contextMenu = Menu.buildFromTemplate([
    {
      label: "显示",
      type: "normal",
      click: () => mainWindow.show(),
    },
    {
      label: "退出",
      type: "normal",
      click: () => {
        mainWindow.destroy();
        app.quit();
      },
    },
  ]);
  tray.setToolTip("课程助手");
  tray.setContextMenu(contextMenu);
}

//主窗口
function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1000,
    height: 800,
    title: "课堂助手",
    show: true,
    titleBarStyle: "hidden", //隐藏窗口标题
    webPreferences: {
      nodeIntegration: true,
      devTools: true,
      defaultEncoding: "utf-8",
    },
  });
  const filePath = path.join(__dirname, "./dist/frontend/index.html");
  mainWindow.loadURL(`file://${filePath}`);

  mainWindow.once("ready-to-show", () => {
    require("./dist/backend/main"); //如果页面启动时需要与nest交互，那么将引入放在第一行
  });
  mainWindow.on("close", function (e) {
    e.preventDefault();
    mainWindow.hide();
  });
}
